﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Web;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
//using www.SService;
using www.Controllerss;
using www.Core.Contract.DataContract;

namespace www.Admin
{
    public partial class PostConfide : System.Web.UI.Page
    {
        #region Value
        //   private readonly SServices _services = new SServices();
        private readonly ObjectCache _cache = MemoryCache.Default;
        static bool _insert = false;
        private static List<RelaxStoryDataContract> _lAdvertiseValue;
        private readonly LanguageController _languageController=new LanguageController();
        private readonly StaffController _staffController=new StaffController();
        private readonly StoryController _storyController=new StoryController();
        private readonly MenuMemberController _menuMemberController=new MenuMemberController();
        private readonly MenuController _menuController=new MenuController();
        private readonly CategoryController _categoryController=new CategoryController();
        //private readonly HyServicesClient _service = new HyServicesClient();
        static int _id = 0;
        private static Boolean _insertNew = false;

        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Cache["Language"] == null)
            {
                var lLanguage = _languageController.GetLanguageDataContracts();
                if (lLanguage.Any())
                    Cache.Insert("Language", lLanguage.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }
            if (_cache["Employee"] == null)
            {
                var lData = _staffController.GetStaffDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Employee", lData.ToList(), policy);
                }
            }

            if (!IsPostBack)
            {
                var lLanguages = (List<RelaxLanguageDataContract>)Cache["Language"];
                if (lLanguages != null)
                {
                    var lReturn = lLanguages.Where(l => l.Id != 1 && l.Type == 1);
                    Addlist(lReturn);
                }
                LoadCategory();
                LoadData();
            }
        }
        #endregion

        #region Event
        protected void ddlgroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void lbtinsert_Click(object sender, EventArgs e)
        {
            pnviews.Visible = false;
            pncontrols.Visible = true;
            Donew();
            _insert = true;
            _id = 0;
            _lAdvertiseValue = null;
        }

        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }

        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_PostConfide.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                _id = Convert.ToInt32(e.CommandArgument);
                var lData = (List<RelaxStoryDataContract>)_cache["News"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == 1);
                if (first == null)
                    return;
                if (e.CommandName == "cmd_edit")
                {
                    txtname.Value = first.Name;
                    txtdecription.Value = first.Decription;
                    txtKeyword.Value = first.Keyword;
                    txtord.Value = first.Priority.ToString();
                    chkactive.Checked = first.Active == 1;
                    ddlCategory.Value = first.CategoryId.ToString();
                    txtDetail.Value = HttpUtility.HtmlDecode(first.Detail);
                    var lValue = lData.Where(p => p.Id == _id && p.Languagecode != 1).ToList();
                    _lAdvertiseValue = lValue;
                    var lReturn = from c in lValue
                                  select new { c.Active, c.Decription, c.Id, c.Keyword, c.Languagecode, c.Name, c.Priority, c.Tag };

                    grvNgonngu.DataSource = lReturn.ToList();
                    grvNgonngu.DataBind();

                    pncontrols.Visible = true;
                    pnviews.Visible = false;
                    _insert = false;

                }
                else if (e.CommandName == "cmd_delete")
                {

                    DeleteLanguage(1);
                    Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                    lData.Remove(first);
                    _cache["News"] = lData;
                    LoadData();
                   
                    Message("Xóa Thành Công");
                    _id = 0;
                    _lAdvertiseValue = null;

                }
                else if (e.CommandName == "cmd_active")
                {
                    first.Active = first.Active == 1 ? 0 : 1;

                    if (_storyController.Update(new List<RelaxStoryDataContract> {first}))
                    {
                        _cache["News"] = lData;
                        LoadData();
                        Message("Cập nhật Thành Công");

                        _id = 0;
                        _lAdvertiseValue = null;
                    }
                   
                }
                else if (e.CommandName == "cmd_Detail")
                {
                    frmDetail.DataSource = new List<RelaxStoryDataContract> { first };
                    frmDetail.DataBind();
                    pnDetail.Visible = true;
                    pnviews.Visible = false;
                    pncontrols.Visible = false;
                }

            }
            catch (Exception)
            {

            }
        }

        protected void grvNgonngu_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var languageCode = e.CommandArgument.ToString();

                if (e.CommandName == "cmd_edit")
                {
                    EditLanguage(Convert.ToInt32(languageCode));
                    _insertNew = true;
                }
                else if (e.CommandName == "cmd_delete")
                {
                    DeleteLanguage(Convert.ToInt32(languageCode));
                }
            }
            catch (Exception)
            {

            }
        }

        protected void grid_PostConfide_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var userId = ((Label)e.Row.FindControl("lblUserId")).Text;
                if (!string.IsNullOrEmpty(userId))
                {
                    var userName = (Label)e.Row.FindControl("lblUserName");
                    var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
                    if (lData != null)
                    {
                        var first = lData.FirstOrDefault(p => p.LoginId == Convert.ToInt32(userId));
                        if (first != null)
                        {
                            userName.Text = first.Name;
                        }
                    }
                }
            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtdonew_Click(object sender, EventArgs e)
        {
            try
            {
                Donew();
            }
            catch (Exception)
            {

            }

        }

        protected void btnThemValue_Click(object sender, EventArgs e)
        {
            try
            {
                var lData = (List<RelaxStoryDataContract>)_cache["News"];
                InsertLanguageCode(lData, _id);
                txtName_Value.Value = txtDecription_Value.Value = txtKeywordValue.Value = txtDetailValue.Value = string.Empty;
                _insertNew = false;
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region Business
        private void LoadStaffMenu()
        {
            if (_cache["StaffMenu"] == null)
            {
                var lData = _menuMemberController.GetMenuMemberDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("StaffMenu", lData.ToList(), policy);
                }
            }
            if (_cache["Menu"] == null)
            {
                var lData = _menuController.GetMenuDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Menu", lData.ToList(), policy);
                }
            }
            if (_cache["Category"] == null)
            {
                var lData = _categoryController.GetCategoryDataContracts();
                var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                _cache.Set("Category", lData.ToList(), policy);
            }
        }
        private void LoadCategory()
        {
            LoadStaffMenu();
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lCategory = (List<RelaxCategoryDataContract>)_cache["Category"];
            if (lMenu == null)
                return;
            if (lMenuStaff == null)
                return;
            if (lCategory == null)
                return;
            var lReturn = (from c in lCategory.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display)
                           join m in lMenu.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display) on c.Id equals m.CategoryId
                           join s in lMenuStaff.Where(p => p.MemberId == Convert.ToInt32(Session["StaffId"]) && p.Active == Constant.Active.Display) on m.Id equals
                    s.MenuId
                           select new { c.Id, c.Name, c.Type }).ToList();
            var tmp = lReturn.ToList();
            foreach (var item in tmp)
            {
                var checkItem = lReturn.Where(p => p.Id == item.Id).ToList();
                if (checkItem.Count > 1)
                {
                    var first = checkItem.FirstOrDefault();
                    foreach (var item1 in checkItem)
                    {
                        lReturn.Remove(item1);
                    }
                    lReturn.Add(first);
                }
            }
            ddlCategory1.Items.Add(new ListItem("---Chọn---", "0"));
            ddlCategory.Items.Add(new ListItem("---Chọn---", "0"));
            var lParent = lReturn.Where(p => p.Type == 0).ToList();
            if (lParent.Any())
            {
                foreach (var item in lParent)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    ddlCategory.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    var lreturn1 = lCategory.Where(p => p.Type == item.Id && p.Languagecode == 1).ToList();
                    if (lreturn1.Any())
                    {
                        foreach (var item1 in lreturn1)
                        {
                            ddlCategory1.Items.Add(new ListItem("--" + item1.Name, item1.Id.ToString()));
                            ddlCategory.Items.Add(new ListItem("--" + item1.Name, item1.Id.ToString()));
                        }
                    }
                }
            }
            else
            {
                foreach (var item in lReturn)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    ddlCategory.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
            }

        }
      
        private void Addlist(IEnumerable<RelaxLanguageDataContract> lLanguageDataContracts)
        {
            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Add(new ListItem("---Chọn---", "0"));
            foreach (var item in lLanguageDataContracts)
            {
                var items = new ListItem(item.Name, item.Id.ToString());
                ddlLanguage.Items.Add(items);
            }
        }
        private void InsertLanguageCode(IEnumerable<RelaxStoryDataContract> lData, int iD = 0)
        {
            if (!string.IsNullOrEmpty(ddlLanguage.Value))
            {
                if (iD > 0)
                {
                    if (_lAdvertiseValue == null)
                    {
                        if (lData != null)
                        {
                            var lVaue =
                                lData.Where(p => p.Id == iD && p.Languagecode != 1).ToList();
                            if (!lVaue.Any())
                                lVaue = new List<RelaxStoryDataContract>();
                            _lAdvertiseValue = lVaue;
                        }
                        else
                            _lAdvertiseValue = new List<RelaxStoryDataContract>();
                    }

                    var languageCode = Convert.ToInt32(ddlLanguage.Value);
                    var check = _lAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
                    if (check.Any())
                    {
                        if (_insertNew)
                        {
                            var firstordefault = check.FirstOrDefault();
                            if (firstordefault != null)
                            {
                                firstordefault.Languagecode = languageCode;
                                firstordefault.Name = txtName_Value.Value.Replace("'", "");
                                firstordefault.Tag = txtName_Value.Value.Replace("'", "").Replace(' ', '-');
                                firstordefault.Decription = txtDecription_Value.Value;
                                firstordefault.Keyword = txtKeywordValue.Value;
                                firstordefault.Detail = HttpUtility.HtmlEncode(txtDetailValue.Value);
                            }
                        }
                        else
                        {
                            Message("Ngôn ngữ này đã tồn tại.");
                            return;
                        }
                    }
                    else
                    {
                        var advertise = new RelaxStoryDataContract
                        {
                            Id = _id,
                            Languagecode = languageCode,
                            Name = txtName_Value.Value.Replace("'", ""),
                            Tag = txtName_Value.Value.Replace("'", "").Replace(' ', '-'),
                            Decription = txtDecription_Value.Value,
                            Keyword = txtKeywordValue.Value,
                            Detail = HttpUtility.HtmlEncode(txtDetailValue.Value)
                        };
                        _lAdvertiseValue.Add(advertise);
                    }
                }
                else
                {
                    if (_lAdvertiseValue == null)
                        _lAdvertiseValue = new List<RelaxStoryDataContract>();

                    var languageCode = Convert.ToInt32(ddlLanguage.Value);
                    var check = _lAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
                    if (check.Any())
                    {
                        if (_insertNew)
                        {
                            var firstordefault = check.FirstOrDefault();
                            if (firstordefault != null)
                            {
                                firstordefault.Languagecode = languageCode;
                                firstordefault.Name = txtName_Value.Value.Replace("'", "");
                                firstordefault.Tag = txtName_Value.Value.Replace("'", "").Replace(' ', '-');
                                firstordefault.Decription = txtDecription_Value.Value;
                                firstordefault.Keyword = txtKeywordValue.Value;
                                firstordefault.Detail = HttpUtility.HtmlEncode(txtDetailValue.Value);
                            }
                        }
                        else
                        {
                            Message("Ngôn ngữ này đã tồn tại.");
                            return;
                        }
                    }
                    else
                    {
                        var advertise = new RelaxStoryDataContract
                        {
                            Languagecode = languageCode,
                            Name = txtName_Value.Value.Replace("'", ""),
                            Tag = txtName_Value.Value.Replace("'", "").Replace(' ', '-'),
                            Decription = txtDecription_Value.Value,
                            Keyword = txtKeywordValue.Value,
                            Detail = HttpUtility.HtmlEncode(txtDetailValue.Value)
                        };
                        _lAdvertiseValue.Add(advertise);
                    }

                }
                grvNgonngu.DataSource = _lAdvertiseValue;
                grvNgonngu.DataBind();

            }
            else
            {
                Message("Bạn phải chọn ngôn ngữ.");
            }
        }

        private void EditLanguage(int iLanguageCode)
        {
            if (iLanguageCode <= 0) return;
            var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
            if (first != null)
            {
                txtName_Value.Value = first.Name;
                txtDecription_Value.Value = first.Decription;
                txtKeywordValue.Value = first.Keyword;
                ddlLanguage.Value = first.Languagecode.ToString();
                txtDetailValue.Value = HttpUtility.HtmlDecode(first.Detail);
            }
        }
        private void DeleteLanguage(int iLanguageCode)
        {
            if (iLanguageCode <= 0) return;

            if (_id > 0)
            {
                _storyController.Delete(new List<long> { _id }, iLanguageCode);
                if (_lAdvertiseValue != null)
                {
                    var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
                    if (first != null)
                    {
                        Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                        _lAdvertiseValue.Remove(first);
                    }
                }
            }
            else
            {
                if (_lAdvertiseValue != null)
                {
                    var first = _lAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
                    if (first != null)
                    {
                        Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                        _lAdvertiseValue.Remove(first);
                    }
                }
            }
            grvNgonngu.DataSource = _lAdvertiseValue;
            grvNgonngu.DataBind();
        }
        private void Save()
        {
            try
            {
                if (string.IsNullOrEmpty(txtname.Value) ||
                    string.IsNullOrEmpty(txtord.Value) || string.IsNullOrEmpty(ddlCategory.Value) || string.IsNullOrEmpty(txtdecription.Value) || string.IsNullOrEmpty(txtDetail.Value) || string.IsNullOrEmpty(txtKeyword.Value))
                {
                    Message("Bạn phải nhập đầy đủ thông tin gợi ý trên");
                    return;
                }
                if (Convert.ToInt32(ddlCategory.Value) <= 0)
                {
                    Message("Bạn phải chọn Danh mục.");
                    return;
                }
                var lData = (List<RelaxStoryDataContract>)_cache["News"];

                var ac = chkactive.Checked ? 1 : 0;
                var path = "Images/News/";
                var postedfile = fuUpload.PostedFile;
                if (postedfile != null)
                {
                    var filename = string.Empty;
                    if (!string.IsNullOrEmpty(postedfile.FileName))
                    {
                        var ext = new FileInfo(postedfile.FileName).Extension;
                        filename = postedfile.FileName.Substring(0,
                            postedfile.FileName.IndexOf(ext, StringComparison.Ordinal));
                        var fn = Convert.ToString(Session["StaffId"]) + "_" + DateTime.Now.Year + "_" +
                                 DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" +
                                 DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Ticks;
                        filename = postedfile.FileName.Replace(filename, fn);
                    }

                    if (!_insert)
                    {
                        var lUpdate = new List<RelaxStoryDataContract>();
                        if (lData == null)
                            return;
                        var first =
                            lData.FirstOrDefault(
                                p => p.Id == _id && p.Languagecode == 1);
                        if (first == null)
                            return;
                        var img = first.Image;
                        if (string.IsNullOrEmpty(filename))
                            path = first.Image;
                        else
                            path += filename;

                        var advertise = new RelaxStoryDataContract
                        {
                            Id = _id,
                            Active = ac,
                            Priority = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                            Keyword = txtKeyword.Value,
                            Name = txtname.Value.Replace("'", ""),
                            Tag = txtname.Value.Replace("'", "").Replace(' ', '-'),
                            Decription = txtdecription.Value,
                            Languagecode = 1,
                            Detail = HttpUtility.HtmlEncode(txtDetail.Value),
                            IsDefault = 0,
                            Image = path,
                            CategoryId = Convert.ToInt32(ddlCategory.Value),
                            Userid = Convert.ToInt32(Session["StaffId"]),
                            Date = first.Date,
                            View = first.View,
                            Report = first.Report,
                            UserBrower = first.UserBrower
                        };
                        lUpdate.Add(advertise);

                        if (_lAdvertiseValue != null && _lAdvertiseValue.Count > 0)
                        {
                            lUpdate.AddRange(_lAdvertiseValue);
                        }
                        if (_storyController.Update(lUpdate))
                        {
                            if (!string.IsNullOrEmpty(filename))
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + img));
                                postedfile.SaveAs(Server.MapPath("~/" + path));
                            }
                            var url = string.Empty;
                            foreach (var item in lUpdate)
                            {
                                var firstordefault =
                                    lData.FirstOrDefault(p => p.Id == item.Id && p.Languagecode == item.Languagecode);
                                if (firstordefault != null)
                                {
                                    firstordefault.Name = item.Name;
                                    firstordefault.Tag = item.Tag;
                                    firstordefault.Priority = lUpdate[0].Priority;
                                    firstordefault.Keyword = item.Keyword;
                                    firstordefault.Decription = item.Decription;
                                    firstordefault.Active = lUpdate[0].Active;
                                    firstordefault.Image = lUpdate[0].Image;
                                    firstordefault.Detail = item.Detail;
                                    firstordefault.Userid = lUpdate[0].Userid;
                                    firstordefault.IsDefault = lUpdate[0].IsDefault;
                                    firstordefault.CategoryId = lUpdate[0].CategoryId;
                                    firstordefault.Date = lUpdate[0].Date;
                                    firstordefault.View = lUpdate[0].View;
                                    firstordefault.UserBrower = lUpdate[0].UserBrower;
                                    firstordefault.Report = lUpdate[0].Report;
                                }
                                else
                                {
                                    item.Priority = lUpdate[0].Priority;
                                    item.Active = lUpdate[0].Active;
                                    item.Image = lUpdate[0].Image;
                                    item.Userid = lUpdate[0].Userid;
                                    item.IsDefault = lUpdate[0].IsDefault;
                                    item.CategoryId = lUpdate[0].CategoryId;
                                    item.Date = lUpdate[0].Date;
                                    item.View = lUpdate[0].View;
                                    item.UserBrower = lUpdate[0].UserBrower;
                                    item.Report = lUpdate[0].Report;
                                    lData.Add(item);
                                }
                                if (lUpdate[0].CategoryId == 9 || lUpdate[0].CategoryId == 10)
                                    url = "http://relax2s.com/Home/NewsDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                                if (lUpdate[0].CategoryId == 11 || lUpdate[0].CategoryId == 12 || lUpdate[0].CategoryId == 13 || lUpdate[0].CategoryId == 14 || lUpdate[0].CategoryId == 15)
                                    url = "http://relax2s.com/Home/StoryDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                                if (lUpdate[0].CategoryId == 16 || lUpdate[0].CategoryId == 17 || lUpdate[0].CategoryId == 18 || lUpdate[0].CategoryId == 19)
                                    url = "http://relax2s.com/Home/AngleSaidDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                                lblMessageLink.InnerHtml += "<div>" + url + "</div>";
                                //_xmlClass.WriteUrl();
                            }

                            _cache["News"] = lData;
                            Message("Sửa Thành Công !");
                            grvNgonngu.DataSource = null;
                            grvNgonngu.DataBind();
                            LoadData();
                            _id = 0;
                            _lAdvertiseValue = null;
                            pncontrols.Visible = false;
                            pnviews.Visible = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(filename))
                        {
                            Message("Ảnh không được bỏ trống.");
                            return;
                        }
                        path += filename;
                        var lAdd = new List<RelaxStoryDataContract>();
                        var advertise = new RelaxStoryDataContract
                        {
                            Active = ac,
                            Name = txtname.Value.Replace("'", ""),
                            Tag = txtname.Value.Replace("'", "").Replace(' ', '-'),
                            Decription = txtdecription.Value,
                            Priority = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                            Keyword = txtKeyword.Value,
                            Languagecode = 1,
                            Detail = HttpUtility.HtmlEncode(txtDetail.Value),
                            IsDefault = 0,
                            View = 0,
                            Image = path,
                            Date = DateTime.Now,
                            CategoryId = Convert.ToInt32(ddlCategory.Value),
                            Userid = Convert.ToInt32(Session["StaffId"]),
                            Report = 0,
                            UserBrower = 0
                        };

                        lAdd.Add(advertise);
                        if (_lAdvertiseValue != null && _lAdvertiseValue.Count > 0)
                        {
                            lAdd.AddRange(_lAdvertiseValue);
                        }

                        var lId = _storyController.Add(lAdd);
                        var url = string.Empty;
                        foreach (var item in lAdd)
                        {
                            item.Priority = lAdd[0].Priority;
                            item.Active = lAdd[0].Active;
                            item.Image = lAdd[0].Image;
                            item.Userid = lAdd[0].Userid;
                            item.IsDefault = lAdd[0].IsDefault;
                            item.CategoryId = lAdd[0].CategoryId;
                            item.Id = lId;
                            item.View = lAdd[0].View;
                            item.Date = lAdd[0].Date;
                            item.UserBrower = lAdd[0].UserBrower;
                            item.Report = lAdd[0].Report;
                            if (lAdd[0].CategoryId == 9 || lAdd[0].CategoryId == 10 )
                                url = "http://relax2s.com/Home/NewsDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                            if (lAdd[0].CategoryId == 11 || lAdd[0].CategoryId == 12 || lAdd[0].CategoryId == 13 || lAdd[0].CategoryId == 14 || lAdd[0].CategoryId==15)
                                url = "http://relax2s.com/Home/StoryDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                            if (lAdd[0].CategoryId == 16 || lAdd[0].CategoryId == 17 || lAdd[0].CategoryId == 18 || lAdd[0].CategoryId == 19)
                                url = "http://relax2s.com/Home/AngleSaidDetail/" + (item.Languagecode == 1 ? "vi-VN" : item.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + item.Id + "/" + item.Tag;
                            lblMessageLink.InnerHtml += "<div>" + url + "</div>";
                            //_xmlClass.WriteUrl();
                        }

                        if (lData == null)
                            lData = new List<RelaxStoryDataContract>();
                        lData.AddRange(lAdd);
                        _cache["News"] = lData;
                        postedfile.SaveAs(Server.MapPath("~/" + path));
                        grvNgonngu.DataSource = null;
                        grvNgonngu.DataBind();
                        Message("Thêm Thành Công !");
                    }
                }
                else
                {
                    Message("Bạn phải chọn ảnh !");
                }
            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnviews.Visible = true;
            pncontrols.Visible = false;
            pnDetail.Visible = false;
            _insert = false;
            _id = 0;
            _lAdvertiseValue = null;
            _insertNew = false;
            LoadData();
        }

        private void Delete()
        {
            try
            {
                if (grid_PostConfide.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_PostConfide.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_PostConfide.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_PostConfide.Rows[i].FindControl("lblId")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                if (_storyController.Delete(lAd, 1))
                {
                    var lData = (List<RelaxStoryDataContract>)_cache["News"];
                    if ((lData.Any()))
                    {
                        foreach (var id in lAd)
                        {
                            var first = lData.FirstOrDefault(p => p.Id == id);
                            if (first != null)
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                                lData.Remove(first);
                            }
                               
                            hang++;
                        }
                    }
                    if (hang != 0)
                    {
                        Message("Có " + hang + "bản ghi được Xóa Thành Công");
                    }
                    else
                    {
                        Message("Không có bản ghi nào được xóa !");

                    }
                    _cache["News"] = lData;
                    LoadData();
                }

            }
            catch { }
        }
        public void LoadData()
        {
            grid_PostConfide.DataSourceID = null;
            if (_cache["News"] == null)
            {
                var lData = _storyController.GetStoryDataContract();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("News", lData.ToList(), policy);
                }
            }
            var lData1 = (List<RelaxStoryDataContract>)_cache["News"];
            if (lData1 != null)
            {
                var lReturn = from c in lData1.Where(p => p.Languagecode == 1 && p.Userid == Convert.ToInt32(Session["StaffId"]) && p.CategoryId == Convert.ToInt32(string.IsNullOrEmpty(ddlCategory1.SelectedValue) ? "0" : ddlCategory1.SelectedValue))
                              select new { c.Active, c.Decription, c.Id, c.Keyword, c.Languagecode, c.Name, c.Priority, c.Tag, c.Image, c.Date, c.Userid };
                grid_PostConfide.DataSource = lReturn.ToList();
            }
            grid_PostConfide.DataBind();
        }

        private void Donew()
        {
            chkactive.Checked = false;
            txtdecription.Value = "";
            txtname.Value = "";
            txtName_Value.Value = "";
            txtDecription_Value.Value = "";
            txtord.Value = "";
            txtKeyword.Value = "";
            txtKeywordValue.Value = "";
            txtDetail.Value = "";
            txtDetailValue.Value = null;
            txtname.Focus();
        }
        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion

      
    }
}